import { observable } from "mobx";
import { observer } from "mobx-react";

import { Form } from "antd";
import { WeaInput, WeaTextarea } from "ecCom";
import { Dialog, ImgUpload } from "../common";

const FormItem = Form.Item;

@observer
class Edit extends React.Component {
    @observable previewDataUrl = null;

    onSave() {
        const previewDataUrl = this.previewDataUrl;
        const { form, onEdit, template, onCancel, onClosed } = this.props;

        form.validateFields(errors => {
            if(errors) return;
            const tmp = form.getFieldsValue();

            tmp.previewImg = previewDataUrl === null ? template.previewImg : previewDataUrl;
            tmp.id = template.id;
            
            let needEdit = false;
            for(let key in tmp) {
                needEdit = needEdit || tmp[key] != template[key];
            }

            needEdit && onEdit(tmp).then(() => {
                onCancel();
                onClosed();
            });
            !needEdit && onCancel();
        });
    }

    onFileChange(base64) {
        this.previewDataUrl = base64;
    }

    render() {
        const { visible, template, onCancel, form } = this.props;
        const { getFieldProps } = form;
        const formItemLayout = {
          labelCol: { span: 6 },
          wrapperCol: { span: 18 },
        };
        const nameProps = getFieldProps("name", {
            rules: [{
                required: true,
                message: "请输入模板名称"
            }],
            initialValue: template.name
        });

        return (
            <Dialog
                visible={visible}
                title="自定义模板: 编辑"
                onOk={this.onSave.bind(this)}
                onCancel={onCancel}>
                <Form form={form} className="template-edit">
                    <FormItem
                        {...formItemLayout}
                        label="名称"
                    >
                        <WeaInput {...nameProps} placeholder="请输入模板名称" />
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="模板分类"
                    >
                        <WeaInput {...getFieldProps("category", { initialValue: template.category }) } />
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="描述"
                    >
                        <WeaTextarea {...getFieldProps("desc", { initialValue: template.desc }) } />
                    </FormItem>
                    <FormItem
                        {...formItemLayout}
                        label="效果图片"
                    >
                        <ImgUpload defaultImg={template.previewImg} onChange={this.onFileChange.bind(this)} />
                    </FormItem>
                </Form>
            </Dialog>
        );
    }
}

Edit = Form.create()(Edit);

export default Edit;